package com.yijinsuo.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * Created by ekikousei易皇星 on 16/12/1.
 * E-mail:13764664731@163.com
 * Signature:缘分是本书,翻的不经意会错过,读的太认真会流泪!!
 * <p>
 * TODO:类描述:   webview post 表单形式访问
 */
public class HtmlFormUtil {

    public static  String makePostHTML(String apiURl,Map<String,String> formData){
        String html = "<!DOCTYPE HTML><html><form id='sbform' action='%s' method='post'>%s</form><script type='text/javascript'>document.getElementById('sbform').submit();</script></body></html>";
        List<String> list = new ArrayList<>(formData.size());
        String input = "<input type='hidden' name='%s' value='%s'/>";
        for(Map.Entry<String,String> entry:formData.entrySet()){
            list.add(String.format(input,entry.getKey(),entry.getValue()));

        }
        return String.format(html, apiURl, org.apache.commons.lang3.StringUtils.join(list, "\n"));
    }

    /**
     * webview参数设置编码UTF-8格式
     * @param paramMap
     * @return
     * @throws Exception
     */
    public static byte[] paramMap2bytes(Map<String, String> paramMap) throws Exception {
        StringBuilder postStrSb = new StringBuilder();
        Object[] set = paramMap.entrySet().toArray();
        for (int i = 0; i < set.length; i++) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) set[i];
            postStrSb.append(String.format("%s=%s", entry.getKey(), (i == set.length - 1 ? entry.getValue() : (entry.getValue() + "&"))));
        }
        return postStrSb.toString().getBytes("UTF-8");
    }

}
